package com.atguigu.gulimall.ware.config;

import com.alibaba.fastjson.JSON;
import com.atguigu.common.to.OrderTo;
import com.atguigu.gulimall.ware.service.WareSkuService;
import com.atguigu.gulimall.ware.to.StockLockedTo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
// 交换机->死信队列->等待过期->交换机->stock.release.stock.queue队列
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {

    @Autowired
    private WareSkuService wareSkuService;

    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo stockLockedTo, Message message, Channel channel){
        System.out.println("收到解锁库存的消息:"+ JSON.toJSONString(stockLockedTo));
        try{
            wareSkuService.unlockStock(stockLockedTo);
            // false 是非批量ack确认,如果为true的话只要有一个ack确认产生那么所有消息全部视为失败会全部重新放回队列中所以必须是false
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try{
                // true表示ack校验失败的消息会重新放回队列中重新ack校验
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }catch (Exception exception){
                System.out.println(e+":{"+e.getMessage()+"}");
            }
        }
    }

    @RabbitHandler
    public void handleOrderClosedToReleaseWare(OrderTo order, Message message, Channel channel){
        System.out.println("收到解锁库存的消息:"+ JSON.toJSONString(order));
        try{
            wareSkuService.releaseWare(order);
            // false 是非批量ack确认,如果为true的话只要有一个ack确认产生那么所有消息全部视为失败会全部重新放回队列中所以必须是false
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            try{
                // true表示ack校验失败的消息会重新放回队列中重新ack校验
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
            }catch (Exception exception){
                System.out.println(e+":{"+e.getMessage()+"}");
            }
        }
    }
}
